#include <stdio.h>
#include <stdlib.h>

typedef struct String {
    char *data;
    int len;
} String;

String *initString()
{
    String *s = (String *)malloc(sizeof(String));
    s->data = NULL;
    s->len = 0;
    return s;
}
//重新赋值的函数
void StringAssign(String *s, char *data) 
{
    if (s->data) free(s->data); 
    int len = 0; //data len
    char *tmp = data;
    while (*tmp++ != '\0') {
      len++;
    }
    if (len == 0) {
        s->data = NULL;
        s->len = 0;
    } else {
        s->data = (char *)malloc(sizeof(char) * (len+1));
        tmp = data;
        s->len = len;
        int i;
        for (i = 0; i < len; i++) {
            s->data[i] = *tmp;
            tmp++;
        }
    }
}

int forceMatch(String *master, String *sub) 
{
    int i = 0; int j = 0;
    while (i < master->len && j < sub->len) {
        if (master->data[i] == sub->data[j]) {
        i++; j++;
        } else {
            j = 0; i = i - j +1; //下标从0开始
        }
    }
    if (j == sub->len) {
            printf("match sucess!\n");
            return i-j;//即 i-1->sub.len+1
    } else {
            printf("match fail!\n");
            return -1;
    }
}

void printString(String *s)
{
    for (int i = 0; i < s->len; i++) {
        printf(i == 0 ? "%c" : "->%c", s->data[i]);
    }
    printf("\n");
}

int main(int argc, char *argv[]) 
{
    String *s = initString();
    StringAssign(s, "hello world");
    printString(s);
    printf("\n---\n");
    char *test = "\0";
    StringAssign(s, test);
    printString(s);

    printf("\n---\n");
    String *t = initString();
    StringAssign(t, "ll");
    printString(t);
    printf("pos: %d\n", forceMatch(s, t));
    return 0;
}